package org.example.springnetty.MyNetty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 服务端业务的Handler
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    private AtomicInteger count = new AtomicInteger(0);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("server accept :"+in.toString(StandardCharsets.UTF_8)+"---"+"And the counter is "+count.incrementAndGet());
        String resp = "hello "+in.toString(StandardCharsets.UTF_8)+" :welcome to the server"+System.lineSeparator();
        ctx.writeAndFlush(Unpooled.copiedBuffer(resp.getBytes(StandardCharsets.UTF_8)));
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
